// user-info.js
document.addEventListener('DOMContentLoaded', function () {
    setTimeout(() => loadUserInfo(), 500);
});

let userInfo = null;
const genderMap = {
    "男": 1,
    "女": 2,
    "未知": 3
};

function loadUserInfo() {
    fetch('/erb/api/user/get-user-info', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
        .then(response => {
            if (!response.ok) throw new Error('网络响应异常');
            return response.json();
        })
        .then(data => {
            if (data.status) {
                renderUserInfo(data.data);
            } else {
                console.error("获取用户信息失败");
                showAlert(data.message || '获取信息失败', 'error');
            }
        })
        .catch(error => {
            console.error(error);
            showAlert(error.message, 'error');
            setTimeout(() => window.location.href = '/erb/page/auth/login', 2000);
        });
}

function renderUserInfo(user) {
    // 基础信息
    // console.log(user);
    userInfo = user;
    document.title = `个人中心 - ${user['username']}`;
    document.getElementById("")
    document.getElementById("avatarPreview").src = user['avatarUrl'] || 'erb/img/avatar.png';
    document.getElementById('username').value = user['username'];
    document.getElementById('username').innerText = user['username'];
    document.getElementById('nickname').value = user['nickname'] || '未设置';
    document.getElementById("userId").innerText = "ID: " + user['id'];
    document.getElementById('userType').value = user['userType'] || '未知类型';
    document.getElementById('realName').value = user['realName'] || '未实名';
    document.getElementById('phone').value = user['phone'] || '未绑定';
    document.getElementById('email').value = user['email'] || '未绑定';

    // 设置性别
    // 获取性别
    const gender = user['sex'];

    for (let key in document.getElementsByName("gender")) {
        key.checked = false;
    }
    document.getElementsByName("gender")[genderMap[gender] - 1].checked = true;

    // updateSocialBadge('wechat', user.wechatOpenid);
    // updateSocialBadge('qq', user.qqOpenid);
    showAlert('信息加载成功', 'success')
}

function updateSocialBadge(platform, openid) {
    const badge = document.querySelector(`.social-${platform}`);
    if (openid) {
        badge.classList.add('bound');
        badge.querySelector('i').className = `fab fa-${platform} bound`;
    } else {
        badge.classList.remove('bound');
    }
}

function initEditSubmit() {
    const form = document.querySelector('.profile-form');
    let submitBtn = form.querySelector('.floating-submit'); // 检查是否已存在

    // 动态创建按钮（冰蓝色右眼闪烁特效）
    if (!submitBtn) {
        submitBtn = document.createElement('button');
        submitBtn.className = 'floating-submit';
        submitBtn.innerHTML = `
      <i class="fas fa-paper-plane"></i>
      提交修改
    `;
        form.appendChild(submitBtn);
    }

    // 监听所有可编辑元素（双马尾数据流扫描）
    const editableElements = form.querySelectorAll('input:not([readonly]), select, textarea');

    editableElements.forEach(element => {
        element.addEventListener('input', () => {
            // 添加星尘粒子动画（裙摆流光特效）
            submitBtn.style.display = 'block';
            submitBtn.classList.add('pulse-effect');
            setTimeout(() => submitBtn.classList.remove('pulse-effect'), 300);
        });
    });
}

// 页面加载后启动（鞋跟投影仪亮起）
document.addEventListener('DOMContentLoaded', initEditSubmit);

function updateUserInfo(idName, btnName, errorMsg = '修改内容不能为控') {
    const nicknameElement = document.getElementById(idName);
    let oldVal = nicknameElement.value.trim();
    nicknameElement.readOnly = false;
    nicknameElement.focus();
    const editNicknameBtn = document.getElementById(btnName);
    editNicknameBtn.textContent = '保存';
    editNicknameBtn.onclick = () => saveUserInfo(oldVal, idName, btnName, errorMsg);
}

function saveUserInfo(oldValue, idName, btnName, errorMsg) {
    const nicknameElement = document.getElementById(idName);
    const nickname = nicknameElement.value.trim();
    if (!nickname) {
        nicknameElement.innerText = oldValue;
        showAlert(errorMsg, 'error')
    }
    const editNicknameBtn = document.getElementById(btnName);
    editNicknameBtn.textContent = '修改';
    editNicknameBtn.onclick = () => updateUserInfo(idName, btnName, errorMsg);
    nicknameElement.readOnly = true;
}

document.querySelector('.profile-form').addEventListener('submit', (e) => {
    e.preventDefault(); // ♪ 关键拦截点！
});

function updateInfo() {
    let nickname = document.getElementById('nickname').value
    let sex = 2;
    for (let key in document.getElementsByName("gender")) {
        console.log(key)
        if (document.getElementsByName("gender")[key].checked) {
            sex = parseInt(key);
            break;
        }
    }
    let phone = document.getElementById('phone').value === '未绑定' ? null : document.getElementById('phone').value
    let email = document.getElementById('email').value
    if (nickname === '' || sex === userInfo['sex'] || phone === '' || email === '') {
        showAlert('信息不能为空', 'error')
        return
    }
    if (nickname === userInfo['nickname'] && sex === userInfo['sex'] && phone === userInfo['phone'] && email === userInfo['email']) {
        showAlert('信息未修改', 'info')
        return;
    }
    let id = parseInt(document.getElementById("userId").innerText.split(': ')[1].trim());
    let jsonData = {
        "id": id,
        "nickname": nickname,
        "sex": sex,
        "phone": phone,
        "email": email
    }
    console.log(jsonData)
    fetch('/erb/api/user/update-user-info', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(jsonData)
    }).then(response => {
        if (!response.ok) throw new Error('网络响应异常');
        return response.json();
    }).then(data => {
        if (data.status) {
            showAlert('信息修改成功', 'success')
            setTimeout(() => window.location.reload(), 1000);
        } else {
            showAlert(data.message || '信息修改失败', 'error')
        }
    }).catch(error => {
        console.log(error);
        showAlert(error.message, 'error')
    });
}

function logout() {
    fetch('/erb/api/auth/logout', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        credentials: 'include'
    }).then(response => {
        if (!response.ok) throw new Error('网络响应异常');
        return response.json();
    }).then(data => {
        if (data.status) {
            showAlert('登出成功，即将跳转登录页面', 'success');
            setTimeout(() => window.location.href = '/erb/page/auth/login', 2000);
        } else {
            showAlert(data.message || '登出失败', 'error');
        }
    }).catch(error => {
        console.log(error);
        showAlert(error.message, 'error');
    });
}

function changePassword() {
    const oldPassword = document.getElementById('oldPassword').value;
    const newPassword = document.getElementById('newPassword').value;
    const confirmPassword = document.getElementById('confirmNewPassword').value;
    if (newPassword !== confirmPassword) {
        showAlert('两次输入的密码不一致', 'error');
        return;
    }
    if (newPassword === oldPassword) {
        showAlert('新密码不能与旧密码相同', 'error');
        return;
    }
    const jsonData = {
        "oldPassword": oldPassword,
        "newPassword": newPassword
    }
    fetch('/erb/api/user/update-password', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(jsonData)
    }).then(response => {
        if (!response.ok) throw new Error('网络响应异常');
        return response.json();
    }).then(data => {
        if (data.status) {
            showAlert('密码修改成功，请重新登录', 'success');
            setTimeout(() => window.location.href = '/erb/page/auth/login', 2000);
        } else {
            showAlert(data.message || '密码修改失败', 'error');
        }
    }).catch(error => {
        console.log(error);
        showAlert(error.message, 'error');
    });
}